"use client"

import { useState } from "react"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import ProjectFlowGraph from "@/components/ProjectFlowGraph"
import FlowOperation from "@/components/FlowOperation"
import { 
  GitBranch, 
  Info, 
  GitPullRequest, 
  CheckSquare, 
  FolderOpen, 
  MessageSquare,
  Settings,
  Edit,
  Download,
  Upload,
  Plus
} from "lucide-react"

interface Project {
  id: string
  projectTitle: string
  projectCode: string
  name: string
  projectType: string
  category: string
  applicationType: string
  description: string
  customerName: string
  applicantName: string
  projectManagerName: string
  level1: string
  level2: string
  level3: string
  level4: string
  statusDesc: string
  priority: string
  createTime: string
  updateTime: string
  startDate: string
  endDate: string
  deadline: string
  planStartDate: string
  planEndDate: string
  hasSample: boolean
  sampleCount: number
  completionPercentage: number
  developmentStatus: string
  progressColor: string
  fullStatusDesc: string
  // 电机参数
  power?: string
  voltage?: string
  current?: string
  ratedSpeed?: string
  ratedTorque?: string
  workTemp?: string
  certification?: string
  lowPower?: string
  startupTime?: string
  conformalCoating?: string
  ratedVoltage?: string
  maxPower?: string
  maxSpeed?: string
  polePairs?: string
  hasHall?: string
  controlMode?: string
  controlAlgorithm?: string
  // 保护参数
  stallProtection?: string
  stallHoldTime?: string
  stallRestartTime?: string
  stallRestartCount?: string
  overvoltageProtection?: string
  overvoltageValue?: string
  overvoltageRecoveryValue?: string
  undervoltageProtection?: string
  undervoltageValue?: string
  undervoltageRecoveryValue?: string
  temperatureProtection?: string
  temperatureValue?: string
  overcurrentProtection?: string
  overcurrentValue?: string
  currentLimitProtection?: string
  currentLimitValue?: string
  blockageProtection?: string
  blockageHoldTime?: string
  blockageRestartTime?: string
  blockageRestartCount?: string
  phaseProtection?: string
  // 控制参数
  controlInterface?: string
  pwmStartDuty?: string
  pwmStopDuty?: string
  pwmDutyRange?: string
  pwmFreqRange?: string
  clockStartFreq?: string
  clockStopFreq?: string
  clockFreqRange?: string
  clockSpeedPowerRange?: string
  clockDuty?: string
  vspStartVoltage?: string
  vspStopVoltage?: string
  vspVoltageRange?: string
  controlDescription?: string
}

interface Branch {
  id: string
  name: string
  isMain: boolean
  isActive: boolean
  level: number
  createTime: string
  creatorName: string
  createTimeFormatted: string
}

interface StateHistory {
  id: string
  fromStateDesc: string
  toStateDesc: string
  createdByName: string
  createdTimeFormatted: string
  comment?: string
}

interface Task {
  id: string
  title: string
  description: string
  status: string
  priority: string
  assigneeName: string
  dueDate: string
  createTime: string
}

interface Resource {
  id: string
  name: string
  type: string
  version: string
  addTime: string
  addTimeDisplay: string
  size: string
  uploaderName: string
}

interface Feedback {
  id: string
  title: string
  content: string
  type: string
  typeDesc: string
  status: string
  statusDesc: string
  submitterName: string
  addTime: string
  addTimeDesc: string
}

interface ProjectDetailTabsProps {
  project: Project
  branches: Branch[]
  stateHistory: StateHistory[]
  tasks: Task[]
  resources: Resource[]
  feedback: Feedback[]
  currentBranch: Branch
  isAdmin: boolean
  isOwner: boolean
  onEditProject?: () => void
  onEditParams?: () => void
  onCreateBranch?: () => void
  onManageBranches?: () => void
  onAddTask?: () => void
  onAddResource?: () => void
  onAddFeedback?: () => void
}

export function ProjectDetailTabs({
  project,
  branches,
  stateHistory,
  tasks,
  resources,
  feedback,
  currentBranch,
  isAdmin,
  isOwner,
  onEditProject,
  onEditParams,
  onCreateBranch,
  onManageBranches,
  onAddTask,
  onAddResource,
  onAddFeedback
}: ProjectDetailTabsProps) {
  const [activeTab, setActiveTab] = useState("overview")

  return (
    <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
      <TabsList className="grid w-full grid-cols-6">
        <TabsTrigger value="graph" className="flex items-center gap-2">
          <GitBranch className="h-4 w-4" />
          <span className="hidden sm:inline">图谱</span>
        </TabsTrigger>
        <TabsTrigger value="overview" className="flex items-center gap-2">
          <Info className="h-4 w-4" />
          <span className="hidden sm:inline">总览</span>
        </TabsTrigger>
        <TabsTrigger value="flow" className="flex items-center gap-2">
          <GitPullRequest className="h-4 w-4" />
          <span className="hidden sm:inline">流转</span>
        </TabsTrigger>
        <TabsTrigger value="tasks" className="flex items-center gap-2">
          <CheckSquare className="h-4 w-4" />
          <span className="hidden sm:inline">任务</span>
        </TabsTrigger>
        <TabsTrigger value="resources" className="flex items-center gap-2">
          <FolderOpen className="h-4 w-4" />
          <span className="hidden sm:inline">资料</span>
        </TabsTrigger>
        <TabsTrigger value="feedback" className="flex items-center gap-2">
          <MessageSquare className="h-4 w-4" />
          <span className="hidden sm:inline">反馈</span>
        </TabsTrigger>
      </TabsList>

      {/* 图谱标签页 */}
      <TabsContent value="graph" className="space-y-4">
        <ProjectFlowGraph 
          projectId={project.id}
          currentStatus={project.level1 || ''}
          histories={project.histories || []}
        />
      </TabsContent>

      {/* 总览标签页 */}
      <TabsContent value="overview" className="space-y-4">
        {/* 基础信息 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Info className="h-5 w-5" />
              基础信息
              {(isAdmin || isOwner) && (
                <Button variant="outline" size="sm" onClick={onEditProject} className="ml-auto">
                  <Edit className="h-4 w-4 mr-2" />
                  编辑
                </Button>
              )}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="flex justify-between">
                <span className="text-gray-500">项目编号：</span>
                <span>{project.projectCode || '无'}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">型号：</span>
                <span>{project.name || '无'}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">项目类型：</span>
                <span>{project.projectType || '未分类'}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">开始时间：</span>
                <span>{project.startDate || '未设置'}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">截止时间：</span>
                <span>{project.deadline || '未设置'}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-500">负责人：</span>
                <span>{project.projectManagerName || '未分配'}</span>
              </div>
            </div>
            {project.description && (
              <div className="mt-4">
                <div className="text-gray-500 mb-2">项目描述：</div>
                <p className="text-gray-700">{project.description}</p>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 电机参数 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Settings className="h-5 w-5" />
              电机参数
              {(isAdmin || isOwner) && (
                <Button variant="outline" size="sm" onClick={onEditParams} className="ml-auto">
                  <Edit className="h-4 w-4 mr-2" />
                  编辑参数
                </Button>
              )}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-6">
              {/* 基本参数 */}
              <div>
                <h4 className="font-medium mb-3 flex items-center gap-2">
                  <span className="text-lg">📋</span>
                  基本参数
                </h4>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {project.power && (
                    <div className="flex justify-between">
                      <span className="text-gray-500">功率：</span>
                      <span>{project.power}W</span>
                    </div>
                  )}
                  {project.voltage && (
                    <div className="flex justify-between">
                      <span className="text-gray-500">电压：</span>
                      <span>{project.voltage}V</span>
                    </div>
                  )}
                  {project.current && (
                    <div className="flex justify-between">
                      <span className="text-gray-500">电流：</span>
                      <span>{project.current}A</span>
                    </div>
                  )}
                  {project.ratedSpeed && (
                    <div className="flex justify-between">
                      <span className="text-gray-500">额定转速：</span>
                      <span>{project.ratedSpeed}rpm</span>
                    </div>
                  )}
                  {project.ratedTorque && (
                    <div className="flex justify-between">
                      <span className="text-gray-500">额定转矩：</span>
                      <span>{project.ratedTorque}Nm</span>
                    </div>
                  )}
                  {project.workTemp && (
                    <div className="flex justify-between">
                      <span className="text-gray-500">工作环境温度：</span>
                      <span>{project.workTemp}℃</span>
                    </div>
                  )}
                  {project.certification && (
                    <div className="flex justify-between">
                      <span className="text-gray-500">认证要求：</span>
                      <span>{project.certification}</span>
                    </div>
                  )}
                  {project.controlMode && (
                    <div className="flex justify-between">
                      <span className="text-gray-500">控制模式：</span>
                      <span>{project.controlMode}</span>
                    </div>
                  )}
                  {project.controlAlgorithm && (
                    <div className="flex justify-between">
                      <span className="text-gray-500">控制算法：</span>
                      <span>{project.controlAlgorithm}</span>
                    </div>
                  )}
                </div>
              </div>

              {/* 保护参数 */}
              {(project.stallProtection || project.overvoltageProtection || project.temperatureProtection) && (
                <div>
                  <h4 className="font-medium mb-3 flex items-center gap-2">
                    <span className="text-lg">🛡️</span>
                    保护参数
                  </h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {project.stallProtection && (
                      <div className="space-y-2">
                        <div className="flex justify-between">
                          <span className="text-gray-500">堵转保护：</span>
                          <span>{project.stallProtection}</span>
                        </div>
                        {project.stallHoldTime && (
                          <div className="flex justify-between ml-4 text-sm">
                            <span className="text-gray-500">保持时间：</span>
                            <span>{project.stallHoldTime}S</span>
                          </div>
                        )}
                        {project.stallRestartTime && (
                          <div className="flex justify-between ml-4 text-sm">
                            <span className="text-gray-500">重启时间：</span>
                            <span>{project.stallRestartTime}S</span>
                          </div>
                        )}
                        {project.stallRestartCount && (
                          <div className="flex justify-between ml-4 text-sm">
                            <span className="text-gray-500">重启次数：</span>
                            <span>{project.stallRestartCount}次</span>
                          </div>
                        )}
                      </div>
                    )}
                    {project.overvoltageProtection && (
                      <div className="space-y-2">
                        <div className="flex justify-between">
                          <span className="text-gray-500">过压保护：</span>
                          <span>{project.overvoltageProtection}</span>
                        </div>
                        {project.overvoltageValue && (
                          <div className="flex justify-between ml-4 text-sm">
                            <span className="text-gray-500">保护值：</span>
                            <span>{project.overvoltageValue}V</span>
                          </div>
                        )}
                      </div>
                    )}
                    {project.temperatureProtection && (
                      <div className="space-y-2">
                        <div className="flex justify-between">
                          <span className="text-gray-500">温度保护：</span>
                          <span>{project.temperatureProtection}</span>
                        </div>
                        {project.temperatureValue && (
                          <div className="flex justify-between ml-4 text-sm">
                            <span className="text-gray-500">保护值：</span>
                            <span>{project.temperatureValue}℃</span>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* 控制参数 */}
              {project.controlInterface && (
                <div>
                  <h4 className="font-medium mb-3 flex items-center gap-2">
                    <span className="text-lg">🎛️</span>
                    控制参数
                  </h4>
                  <div className="space-y-4">
                    <div className="flex justify-between">
                      <span className="text-gray-500">控制接口：</span>
                      <span>{project.controlInterface}</span>
                    </div>
                    
                    {project.controlInterface === 'PWM控制' && (
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4 ml-4">
                        {project.pwmStartDuty && (
                          <div className="flex justify-between">
                            <span className="text-gray-500">开机点占空比：</span>
                            <span>{project.pwmStartDuty}%</span>
                          </div>
                        )}
                        {project.pwmStopDuty && (
                          <div className="flex justify-between">
                            <span className="text-gray-500">关机点占空比：</span>
                            <span>{project.pwmStopDuty}%</span>
                          </div>
                        )}
                        {project.pwmDutyRange && (
                          <div className="flex justify-between">
                            <span className="text-gray-500">有效占空比：</span>
                            <span>{project.pwmDutyRange}%</span>
                          </div>
                        )}
                        {project.pwmFreqRange && (
                          <div className="flex justify-between">
                            <span className="text-gray-500">频率范围：</span>
                            <span>{project.pwmFreqRange}Hz</span>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* 补充功能描述 */}
              {project.controlDescription && (
                <div>
                  <h4 className="font-medium mb-3 flex items-center gap-2">
                    <span className="text-lg">📝</span>
                    补充功能描述
                  </h4>
                  <p className="text-gray-700 bg-gray-50 p-3 rounded">
                    {project.controlDescription}
                  </p>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </TabsContent>

      {/* 流转标签页 */}
      <TabsContent value="flow" className="space-y-4">
        <FlowOperation 
          projectId={project.id}
          currentStatus={project.level1 || ''}
          onFlowSubmit={async (data) => {
            try {
              const formData = new FormData()
              formData.append('transitionId', data.transitionId)
              formData.append('note', data.note)
              formData.append('description', data.description)
              
              // 添加文件
              data.attachments.forEach(file => {
                formData.append('files', file)
              })
              
              const response = await fetch(`/api/projects/${project.id}/flow`, {
                method: 'POST',
                body: formData
              })
              
              if (response.ok) {
                const result = await response.json()
                console.log('Flow operation successful:', result)
                // 可以在这里添加成功提示或刷新页面数据
              } else {
                console.error('Flow operation failed:', response.statusText)
              }
            } catch (error) {
              console.error('Error submitting flow operation:', error)
            }
          }}
        />
        
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <GitPullRequest className="h-5 w-5" />
              历史流转记录
            </CardTitle>
          </CardHeader>
          <CardContent>
            {stateHistory.length > 0 ? (
              <div className="space-y-4">
                {stateHistory.map((history) => (
                  <div key={history.id} className="flex gap-4">
                    <div className="flex flex-col items-center">
                      <div className="w-3 h-3 bg-blue-500 rounded-full"></div>
                      <div className="w-0.5 h-16 bg-gray-200"></div>
                    </div>
                    <div className="flex-1">
                      <div className="flex justify-between items-start mb-2">
                        <div className="flex items-center gap-2">
                          <span className="font-medium">{history.createdByName}</span>
                          <Badge variant="outline">
                            {history.fromStateDesc} → {history.toStateDesc}
                          </Badge>
                        </div>
                        <span className="text-sm text-gray-500">{history.createdTimeFormatted}</span>
                      </div>
                      {history.comment && (
                        <p className="text-gray-600 text-sm bg-gray-50 p-2 rounded">
                          {history.comment}
                        </p>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8">
                <GitPullRequest className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-500">暂无状态流转记录</p>
              </div>
            )}
          </CardContent>
        </Card>
      </TabsContent>

      {/* 任务标签页 */}
      <TabsContent value="tasks" className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <CheckSquare className="h-5 w-5" />
              任务管理
              <Button variant="outline" size="sm" onClick={onAddTask} className="ml-auto">
                <Plus className="h-4 w-4 mr-2" />
                添加任务
              </Button>
            </CardTitle>
          </CardHeader>
          <CardContent>
            {tasks.length > 0 ? (
              <div className="space-y-3">
                {tasks.map((task) => (
                  <div key={task.id} className="flex items-center justify-between p-3 border rounded-lg">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <span className="font-medium">{task.title}</span>
                        <Badge variant={
                          task.status === 'COMPLETED' ? 'default' :
                          task.status === 'IN_PROGRESS' ? 'secondary' :
                          task.status === 'PENDING' ? 'outline' : 'destructive'
                        }>
                          {task.status}
                        </Badge>
                        <Badge variant={
                          task.priority === 'HIGH' ? 'destructive' :
                          task.priority === 'MEDIUM' ? 'default' : 'secondary'
                        }>
                          {task.priority}
                        </Badge>
                      </div>
                      <p className="text-sm text-gray-600 mb-1">{task.description}</p>
                      <div className="flex items-center gap-4 text-xs text-gray-500">
                        <span>负责人: {task.assigneeName}</span>
                        <span>截止: {task.dueDate}</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8">
                <CheckSquare className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-500 mb-4">暂无任务</p>
                <Button onClick={onAddTask}>
                  <Plus className="h-4 w-4 mr-2" />
                  添加任务
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      </TabsContent>

      {/* 资料标签页 */}
      <TabsContent value="resources" className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FolderOpen className="h-5 w-5" />
              项目资料
              {(isAdmin || isOwner) && (
                <Button variant="outline" size="sm" onClick={onAddResource} className="ml-auto">
                  <Upload className="h-4 w-4 mr-2" />
                  上传资料
                </Button>
              )}
            </CardTitle>
          </CardHeader>
          <CardContent>
            {resources.length > 0 ? (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {resources.map((resource) => (
                  <div key={resource.id} className="border rounded-lg p-4 hover:shadow-md transition-shadow">
                    <div className="flex items-start justify-between mb-2">
                      <div className="flex items-center gap-2">
                        <FolderOpen className="h-5 w-5 text-blue-500" />
                        <span className="font-medium text-sm">{resource.name}</span>
                      </div>
                      <Badge variant="outline" className="text-xs">
                        v{resource.version}
                      </Badge>
                    </div>
                    <div className="text-xs text-gray-500 space-y-1">
                      <div>类型: {resource.type}</div>
                      <div>大小: {resource.size}</div>
                      <div>上传者: {resource.uploaderName}</div>
                      <div>时间: {resource.addTimeDisplay}</div>
                    </div>
                    <div className="flex gap-2 mt-3">
                      <Button variant="outline" size="sm" className="flex-1">
                        查看
                      </Button>
                      <Button variant="outline" size="sm" className="flex-1">
                        <Download className="h-3 w-3" />
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8">
                <FolderOpen className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-500 mb-4">暂无资料</p>
                {(isAdmin || isOwner) && (
                  <Button onClick={onAddResource}>
                    <Upload className="h-4 w-4 mr-2" />
                    上传资料
                  </Button>
                )}
              </div>
            )}
          </CardContent>
        </Card>
      </TabsContent>

      {/* 反馈标签页 */}
      <TabsContent value="feedback" className="space-y-4">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <MessageSquare className="h-5 w-5" />
              项目反馈
              <Button variant="outline" size="sm" onClick={onAddFeedback} className="ml-auto">
                <Plus className="h-4 w-4 mr-2" />
                添加反馈
              </Button>
            </CardTitle>
          </CardHeader>
          <CardContent>
            {feedback.length > 0 ? (
              <div className="space-y-4">
                {feedback.map((item) => (
                  <div key={item.id} className="border rounded-lg p-4">
                    <div className="flex items-start justify-between mb-2">
                      <div className="flex items-center gap-2">
                        <span className="font-medium">{item.title}</span>
                        <Badge variant="outline">{item.typeDesc}</Badge>
                        <Badge variant={
                          item.status === 'RESOLVED' ? 'default' :
                          item.status === 'IN_PROGRESS' ? 'secondary' :
                          item.status === 'PENDING' ? 'outline' : 'destructive'
                        }>
                          {item.statusDesc}
                        </Badge>
                      </div>
                    </div>
                    <p className="text-gray-600 text-sm mb-3">{item.content}</p>
                    <div className="flex items-center gap-4 text-xs text-gray-500">
                      <span>提交者: {item.submitterName}</span>
                      <span>时间: {item.addTimeDesc}</span>
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8">
                <MessageSquare className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-500 mb-2">暂无反馈记录</p>
                <p className="text-gray-400 text-sm mb-4">点击"添加反馈"按钮提交新的反馈</p>
                <Button onClick={onAddFeedback}>
                  <Plus className="h-4 w-4 mr-2" />
                  添加反馈
                </Button>
              </div>
            )}
          </CardContent>
        </Card>
      </TabsContent>
    </Tabs>
  )
}